package com.shopping_back.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shopping_back.common.Result;
import com.shopping_back.pojo.entity.User;
import com.shopping_back.service.IUserService;
import com.shopping_back.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private TokenUtil tokenUtil;

    @PostMapping("/api/login")
    public Result login(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, user.getPassword());

        User loginUser = userService.getOne(queryWrapper);
        if (loginUser != null) {
            JSONObject json = JSONUtil.createObj()
                    .set("userId", loginUser.getId())
                    .set("username", loginUser.getUsername())
                    .set("identity", "admin");
            String token = tokenUtil.createToken(json);
            JSONObject data = JSONUtil.createObj()
                    .set("token", token)
                    .set("userId", loginUser.getId())
                    .set("username", loginUser.getUsername());
            return Result.success(data);
        }
        return Result.error("用户名或密码错误");
    }
}
